// 个人中心页面功能
class ProfileManager {
    constructor() {
        this.currentUser = null;
        this.currentTab = 'posts';
        this.currentPage = {
            posts: 1,
            favorites: 1,
            comments: 1
        };
        this.pageSize = 10;
        this.categories = [];
        
        this.init();
    }

    init() {
        this.checkAuth();
        this.bindEvents();
        this.loadUserProfile();
        this.loadCategories();
        this.loadTabContent('posts');
    }

    checkAuth() {
        const token = localStorage.getItem('token');
        const user = localStorage.getItem('user');
        
        if (!token || !user) {
            window.location.href = 'index.html';
            return;
        }
        
        this.currentUser = JSON.parse(user);
        this.updateUserInfo();
    }

    updateUserInfo() {
        document.getElementById('username').textContent = this.currentUser.username;
        document.getElementById('userName').textContent = this.currentUser.username;
        document.getElementById('userEmail').textContent = this.currentUser.email || '未设置邮箱';
        document.getElementById('userJoinDate').textContent = this.formatDate(this.currentUser.created_at);
        
        // 设置表单默认值
        document.getElementById('profileUsername').value = this.currentUser.username;
        document.getElementById('profileEmail').value = this.currentUser.email || '';
    }

    bindEvents() {
        // 主题切换
        document.getElementById('themeToggle').addEventListener('click', () => {
            this.toggleTheme();
        });

        // 退出登录
        document.getElementById('logoutBtn').addEventListener('click', () => {
            this.logout();
        });

        // 标签页切换
        document.querySelectorAll('.profile-nav .nav-item').forEach(item => {
            item.addEventListener('click', (e) => {
                e.preventDefault();
                const tab = item.dataset.tab;
                this.switchTab(tab);
            });
        });

        // 发布新帖子
        document.getElementById('newPostBtn').addEventListener('click', () => {
            document.getElementById('newPostModal').style.display = 'flex';
        });

        // 模态框关闭
        document.getElementById('newPostModalClose').addEventListener('click', () => {
            document.getElementById('newPostModal').style.display = 'none';
        });

        document.getElementById('editPostModalClose').addEventListener('click', () => {
            document.getElementById('editPostModal').style.display = 'none';
        });

        document.getElementById('cancelPost').addEventListener('click', () => {
            document.getElementById('newPostModal').style.display = 'none';
        });

        document.getElementById('cancelEdit').addEventListener('click', () => {
            document.getElementById('editPostModal').style.display = 'none';
        });

        // 表单提交
        document.getElementById('newPostForm').addEventListener('submit', (e) => {
            this.handleNewPost(e);
        });

        document.getElementById('editPostForm').addEventListener('submit', (e) => {
            this.handleEditPost(e);
        });

        document.getElementById('profileForm').addEventListener('submit', (e) => {
            this.handleProfileUpdate(e);
        });

        document.getElementById('resetForm').addEventListener('click', () => {
            this.resetProfileForm();
        });

        // 点击模态框外部关闭
        window.addEventListener('click', (e) => {
            if (e.target.classList.contains('modal')) {
                e.target.style.display = 'none';
            }
        });
    }

    switchTab(tab) {
        // 更新导航状态
        document.querySelectorAll('.profile-nav .nav-item').forEach(item => {
            item.classList.remove('active');
        });
        document.querySelector(`[data-tab="${tab}"]`).classList.add('active');

        // 更新内容区域
        document.querySelectorAll('.tab-content').forEach(content => {
            content.classList.remove('active');
        });
        document.getElementById(`${tab}Tab`).classList.add('active');

        this.currentTab = tab;
        this.loadTabContent(tab);
    }

    async loadTabContent(tab) {
        switch (tab) {
            case 'posts':
                await this.loadUserPosts();
                break;
            case 'favorites':
                await this.loadUserFavorites();
                break;
            case 'comments':
                await this.loadUserComments();
                break;
            case 'settings':
                // 设置页面不需要额外加载
                break;
        }
    }

    async loadUserProfile() {
        try {
            const response = await fetch('/api/v1/users/profile', {
                headers: {
                    'Authorization': `Bearer ${localStorage.getItem('token')}`
                }
            });

            if (response.ok) {
                const result = await response.json();
                const stats = result.data.stats || {};
                
                document.getElementById('postCount').textContent = stats.posts || 0;
                document.getElementById('favoriteCount').textContent = stats.favorites || 0;
                document.getElementById('likeCount').textContent = stats.likes || 0;
            }
        } catch (error) {
            console.error('加载用户资料失败:', error);
        }
    }

    async loadCategories() {
        try {
            const response = await fetch('/api/v1/categories');
            if (response.ok) {
                const result = await response.json();
                this.categories = result.data || [];
                this.updateCategorySelects();
            }
        } catch (error) {
            console.error('加载分类失败:', error);
        }
    }

    updateCategorySelects() {
        const selects = ['postCategory', 'editPostCategory'];
        selects.forEach(selectId => {
            const select = document.getElementById(selectId);
            select.innerHTML = '<option value="">选择分类</option>';
            this.categories.forEach(category => {
                const option = document.createElement('option');
                option.value = category.id;
                option.textContent = category.name;
                select.appendChild(option);
            });
        });
    }

    async loadUserPosts() {
        const loading = document.getElementById('postsLoading');
        const container = document.getElementById('userPostsList');
        
        loading.style.display = 'block';
        
        try {
            const response = await fetch(`/api/v1/users/posts?page=${this.currentPage.posts}&page_size=${this.pageSize}`, {
                headers: {
                    'Authorization': `Bearer ${localStorage.getItem('token')}`
                }
            });

            if (response.ok) {
                const result = await response.json();
                const posts = result.data || [];
                this.renderUserPosts(posts);
                this.renderPagination('posts', result.total || 0);
            } else {
                this.showEmptyState('posts', '获取帖子失败');
            }
        } catch (error) {
            console.error('加载用户帖子失败:', error);
            this.showEmptyState('posts', '加载失败，请稍后重试');
        } finally {
            loading.style.display = 'none';
        }
    }

    renderUserPosts(posts) {
        const container = document.getElementById('userPostsList');
        
        if (!posts || posts.length === 0) {
            this.showEmptyState('posts', '您还没有发布任何帖子');
            return;
        }

        container.innerHTML = posts.map(post => `
            <div class="post-item">
                <div class="post-item-header">
                    <div>
                        <h3 class="post-item-title" onclick="window.location.href='post.html?id=${post.id}'">
                            ${post.title}
                        </h3>
                        <div class="post-item-meta">
                            <span>分类: ${post.category_name || '未分类'}</span>
                            <span>发布时间: ${this.formatDate(post.created_at)}</span>
                            <span>状态: ${post.status === 'published' ? '已发布' : '草稿'}</span>
                        </div>
                    </div>
                    <div class="post-item-actions">
                        <button class="action-btn-sm edit" onclick="profileManager.editPost(${post.id})">
                            编辑
                        </button>
                        <button class="action-btn-sm delete" onclick="profileManager.deletePost(${post.id})">
                            删除
                        </button>
                    </div>
                </div>
                <p class="post-item-excerpt">${post.summary || post.content.substring(0, 150) + '...'}</p>
                <div class="post-item-footer">
                    <div class="post-item-stats">
                        <span>👁️ ${post.views || 0} 浏览</span>
                        <span>👍 ${post.likes || 0} 点赞</span>
                        <span>💬 ${post.comments || 0} 评论</span>
                    </div>
                </div>
            </div>
        `).join('');
    }

    async loadUserFavorites() {
        const loading = document.getElementById('favoritesLoading');
        const container = document.getElementById('favoritesList');
        
        loading.style.display = 'block';
        
        try {
            const response = await fetch(`/api/v1/users/favorites?page=${this.currentPage.favorites}&page_size=${this.pageSize}`, {
                headers: {
                    'Authorization': `Bearer ${localStorage.getItem('token')}`
                }
            });

            if (response.ok) {
                const result = await response.json();
                const favorites = result.data || [];
                this.renderUserFavorites(favorites);
                this.renderPagination('favorites', result.total || 0);
            } else {
                this.showEmptyState('favorites', '获取收藏失败');
            }
        } catch (error) {
            console.error('加载用户收藏失败:', error);
            this.showEmptyState('favorites', '加载失败，请稍后重试');
        } finally {
            loading.style.display = 'none';
        }
    }

    renderUserFavorites(favorites) {
        const container = document.getElementById('favoritesList');
        
        if (!favorites || favorites.length === 0) {
            this.showEmptyState('favorites', '您还没有收藏任何帖子');
            return;
        }

        container.innerHTML = favorites.map(item => `
            <div class="post-item">
                <div class="post-item-header">
                    <div>
                        <h3 class="post-item-title" onclick="window.location.href='post.html?id=${item.post.id}'">
                            ${item.post.title}
                        </h3>
                        <div class="post-item-meta">
                            <span>作者: ${item.post.author || '匿名用户'}</span>
                            <span>收藏时间: ${this.formatDate(item.created_at)}</span>
                        </div>
                    </div>
                    <div class="post-item-actions">
                        <button class="action-btn-sm delete" onclick="profileManager.removeFavorite(${item.post.id})">
                            取消收藏
                        </button>
                    </div>
                </div>
                <p class="post-item-excerpt">${item.post.summary || item.post.content.substring(0, 150) + '...'}</p>
            </div>
        `).join('');
    }

    async loadUserComments() {
        const loading = document.getElementById('commentsLoading');
        const container = document.getElementById('userCommentsList');
        
        loading.style.display = 'block';
        
        try {
            const response = await fetch(`/api/v1/users/comments?page=${this.currentPage.comments}&page_size=${this.pageSize}`, {
                headers: {
                    'Authorization': `Bearer ${localStorage.getItem('token')}`
                }
            });

            if (response.ok) {
                const result = await response.json();
                const comments = result.data || [];
                this.renderUserComments(comments);
                this.renderPagination('comments', result.total || 0);
            } else {
                this.showEmptyState('comments', '获取评论失败');
            }
        } catch (error) {
            console.error('加载用户评论失败:', error);
            this.showEmptyState('comments', '加载失败，请稍后重试');
        } finally {
            loading.style.display = 'none';
        }
    }

    renderUserComments(comments) {
        const container = document.getElementById('userCommentsList');
        
        if (!comments || comments.length === 0) {
            this.showEmptyState('comments', '您还没有发表任何评论');
            return;
        }

        container.innerHTML = comments.map(comment => `
            <div class="comment-item">
                <div class="comment-item-header">
                    <a href="post.html?id=${comment.post.id}" class="comment-post-title">
                        ${comment.post.title}
                    </a>
                    <span class="comment-date">${this.formatDate(comment.created_at)}</span>
                </div>
                <div class="comment-content">${comment.content}</div>
            </div>
        `).join('');
    }

    showEmptyState(type, message) {
        const containers = {
            posts: 'userPostsList',
            favorites: 'favoritesList',
            comments: 'userCommentsList'
        };
        
        const icons = {
            posts: '📝',
            favorites: '⭐',
            comments: '💬'
        };
        
        const container = document.getElementById(containers[type]);
        container.innerHTML = `
            <div class="empty-state">
                <div class="icon">${icons[type]}</div>
                <h3>暂无内容</h3>
                <p>${message}</p>
                ${type === 'posts' ? '<button class="btn btn-primary" onclick="document.getElementById(\'newPostBtn\').click()">发布第一篇帖子</button>' : ''}
            </div>
        `;
    }

    renderPagination(type, total) {
        const totalPages = Math.ceil(total / this.pageSize);
        const currentPage = this.currentPage[type];
        const containerId = `${type}Pagination`;
        const container = document.getElementById(containerId);
        
        if (totalPages <= 1) {
            container.innerHTML = '';
            return;
        }
        
        let pagination = '<button onclick="profileManager.changePage(\''+type+'\', 1)" ' + (currentPage === 1 ? 'disabled' : '') + '>首页</button>';
        pagination += '<button onclick="profileManager.changePage(\''+type+'\', '+(currentPage-1)+')" ' + (currentPage === 1 ? 'disabled' : '') + '>上一页</button>';
        
        for (let i = Math.max(1, currentPage - 2); i <= Math.min(totalPages, currentPage + 2); i++) {
            pagination += '<button onclick="profileManager.changePage(\''+type+'\', '+i+')" ' + (i === currentPage ? 'class="active"' : '') + '>'+i+'</button>';
        }
        
        pagination += '<button onclick="profileManager.changePage(\''+type+'\', '+(currentPage+1)+')" ' + (currentPage === totalPages ? 'disabled' : '') + '>下一页</button>';
        pagination += '<button onclick="profileManager.changePage(\''+type+'\', '+totalPages+')" ' + (currentPage === totalPages ? 'disabled' : '') + '>末页</button>';
        
        container.innerHTML = pagination;
    }

    changePage(type, page) {
        this.currentPage[type] = page;
        this.loadTabContent(type);
    }

    async handleNewPost(e) {
        e.preventDefault();
        
        const title = document.getElementById('postTitle').value.trim();
        const categoryId = document.getElementById('postCategory').value;
        const content = document.getElementById('postContent').value.trim();
        const autoClassify = document.getElementById('autoClassify').checked;
        const autoSummary = document.getElementById('autoSummary').checked;
        
        if (!title || !content) {
            this.showNotification('请填写标题和内容', 'warning');
            return;
        }
        
        try {
            const response = await fetch('/api/v1/posts', {
                method: 'POST',
                headers: {
                    'Authorization': `Bearer ${localStorage.getItem('token')}`,
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    title,
                    content,
                    category_id: categoryId ? parseInt(categoryId) : undefined,
                    auto_classify: autoClassify,
                    auto_summary: autoSummary
                })
            });
            
            if (response.ok) {
                document.getElementById('newPostModal').style.display = 'none';
                document.getElementById('newPostForm').reset();
                this.showNotification('帖子发布成功', 'success');
                this.loadUserPosts();
                this.loadUserProfile(); // 更新统计
            } else {
                const result = await response.json();
                this.showNotification(result.error || '发布失败', 'error');
            }
        } catch (error) {
            console.error('发布帖子失败:', error);
            this.showNotification('发布失败，请稍后重试', 'error');
        }
    }

    async editPost(postId) {
        try {
            const response = await fetch(`/api/v1/posts/${postId}`, {
                headers: {
                    'Authorization': `Bearer ${localStorage.getItem('token')}`
                }
            });
            
            if (response.ok) {
                const result = await response.json();
                const post = result.data;
                
                document.getElementById('editPostId').value = post.id;
                document.getElementById('editPostTitle').value = post.title;
                document.getElementById('editPostCategory').value = post.category_id || '';
                document.getElementById('editPostContent').value = post.content;
                
                document.getElementById('editPostModal').style.display = 'flex';
            } else {
                this.showNotification('获取帖子信息失败', 'error');
            }
        } catch (error) {
            console.error('获取帖子信息失败:', error);
            this.showNotification('获取帖子信息失败', 'error');
        }
    }

    async handleEditPost(e) {
        e.preventDefault();
        
        const postId = document.getElementById('editPostId').value;
        const title = document.getElementById('editPostTitle').value.trim();
        const categoryId = document.getElementById('editPostCategory').value;
        const content = document.getElementById('editPostContent').value.trim();
        
        if (!title || !content) {
            this.showNotification('请填写标题和内容', 'warning');
            return;
        }
        
        try {
            const response = await fetch(`/api/v1/posts/${postId}`, {
                method: 'PUT',
                headers: {
                    'Authorization': `Bearer ${localStorage.getItem('token')}`,
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    title,
                    content,
                    category_id: categoryId ? parseInt(categoryId) : undefined
                })
            });
            
            if (response.ok) {
                document.getElementById('editPostModal').style.display = 'none';
                this.showNotification('帖子更新成功', 'success');
                this.loadUserPosts();
            } else {
                const result = await response.json();
                this.showNotification(result.error || '更新失败', 'error');
            }
        } catch (error) {
            console.error('更新帖子失败:', error);
            this.showNotification('更新失败，请稍后重试', 'error');
        }
    }

    async deletePost(postId) {
        if (!confirm('确定要删除这篇帖子吗？此操作不可撤销。')) {
            return;
        }
        
        try {
            const response = await fetch(`/api/v1/posts/${postId}`, {
                method: 'DELETE',
                headers: {
                    'Authorization': `Bearer ${localStorage.getItem('token')}`
                }
            });
            
            if (response.ok) {
                this.showNotification('帖子删除成功', 'success');
                this.loadUserPosts();
                this.loadUserProfile(); // 更新统计
            } else {
                const result = await response.json();
                this.showNotification(result.error || '删除失败', 'error');
            }
        } catch (error) {
            console.error('删除帖子失败:', error);
            this.showNotification('删除失败，请稍后重试', 'error');
        }
    }

    async removeFavorite(postId) {
        try {
            const response = await fetch(`/api/v1/posts/${postId}/favorite`, {
                method: 'DELETE',
                headers: {
                    'Authorization': `Bearer ${localStorage.getItem('token')}`
                }
            });
            
            if (response.ok) {
                this.showNotification('取消收藏成功', 'success');
                this.loadUserFavorites();
                this.loadUserProfile(); // 更新统计
            } else {
                this.showNotification('操作失败', 'error');
            }
        } catch (error) {
            console.error('取消收藏失败:', error);
            this.showNotification('操作失败，请稍后重试', 'error');
        }
    }

    async handleProfileUpdate(e) {
        e.preventDefault();
        
        const email = document.getElementById('profileEmail').value.trim();
        const bio = document.getElementById('profileBio').value.trim();
        const currentPassword = document.getElementById('currentPassword').value;
        const newPassword = document.getElementById('newPassword').value;
        const confirmPassword = document.getElementById('confirmPassword').value;
        
        // 验证密码
        if (newPassword && newPassword !== confirmPassword) {
            this.showNotification('新密码和确认密码不匹配', 'warning');
            return;
        }
        
        if (newPassword && !currentPassword) {
            this.showNotification('请输入当前密码', 'warning');
            return;
        }
        
        try {
            const updateData = { email, bio };
            if (newPassword) {
                updateData.current_password = currentPassword;
                updateData.new_password = newPassword;
            }
            
            const response = await fetch('/api/v1/users/profile', {
                method: 'PUT',
                headers: {
                    'Authorization': `Bearer ${localStorage.getItem('token')}`,
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(updateData)
            });
            
            if (response.ok) {
                this.showNotification('资料更新成功', 'success');
                // 清空密码字段
                document.getElementById('currentPassword').value = '';
                document.getElementById('newPassword').value = '';
                document.getElementById('confirmPassword').value = '';
                
                // 更新本地用户信息
                if (email !== this.currentUser.email) {
                    this.currentUser.email = email;
                    localStorage.setItem('user', JSON.stringify(this.currentUser));
                    this.updateUserInfo();
                }
            } else {
                const result = await response.json();
                this.showNotification(result.error || '更新失败', 'error');
            }
        } catch (error) {
            console.error('更新资料失败:', error);
            this.showNotification('更新失败，请稍后重试', 'error');
        }
    }

    resetProfileForm() {
        document.getElementById('profileEmail').value = this.currentUser.email || '';
        document.getElementById('profileBio').value = '';
        document.getElementById('currentPassword').value = '';
        document.getElementById('newPassword').value = '';
        document.getElementById('confirmPassword').value = '';
    }

    logout() {
        localStorage.removeItem('token');
        localStorage.removeItem('user');
        window.location.href = 'index.html';
    }

    toggleTheme() {
        const body = document.body;
        const themeIcon = document.querySelector('.theme-icon');
        
        body.classList.toggle('dark-theme');
        themeIcon.textContent = body.classList.contains('dark-theme') ? '☀️' : '🌙';
        
        localStorage.setItem('theme', body.classList.contains('dark-theme') ? 'dark' : 'light');
    }

    formatDate(dateString) {
        const date = new Date(dateString);
        return date.toLocaleDateString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit'
        });
    }

    showNotification(message, type = 'info') {
        // 创建通知元素
        const notification = document.createElement('div');
        notification.className = `notification notification-${type}`;
        notification.textContent = message;
        
        // 添加到页面
        document.body.appendChild(notification);
        
        // 显示动画
        setTimeout(() => notification.classList.add('show'), 100);
        
        // 自动隐藏
        setTimeout(() => {
            notification.classList.remove('show');
            setTimeout(() => notification.remove(), 300);
        }, 3000);
    }
}

// 初始化主题
function initTheme() {
    const savedTheme = localStorage.getItem('theme');
    const themeIcon = document.querySelector('.theme-icon');
    
    if (savedTheme === 'dark') {
        document.body.classList.add('dark-theme');
        themeIcon.textContent = '☀️';
    } else {
        themeIcon.textContent = '🌙';
    }
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', () => {
    initTheme();
    window.profileManager = new ProfileManager();
});